package com.example.demo.config.datasource;

import com.example.demo.config.annotation.SwitchSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: njz
 * @Description:
 * @Date: create in 2022/6/6 14:20
 */
@Aspect
//优先级要设置在事务切面执行之前
@Order(1)
@Component
@Slf4j
public class DataSourceAspect {

    /**
     * 在方法执行之前切换到指定的数据源
     * @param joinPoint
     */
    @Before(value = "@annotation(switchSource)")
    public void beforeOpt(JoinPoint joinPoint,SwitchSource switchSource) {
        log.info("[Switch DataSource]:" + switchSource.value());
        DataSourceHolder.setDataSource(switchSource.value());
    }

    /**
     * 方法执行之后清除掉ThreadLocal中存储的KEY，这样动态数据源会使用默认的数据源
     */
    @After(value = "@annotation(switchSource)")
    public void afterOpt(SwitchSource switchSource) {
        DataSourceHolder.clearDataSource();
        log.info("[Switch Default DataSource]:"+switchSource.value());
    }
}
